import Vue from 'vue'
import VueRouter from 'vue-router'

// 进度条
import NProgress from 'nprogress'
import 'nprogress/nprogress.css'

import store from '@/store/index'
import util from '@/libs/util.js'

// 由于懒加载页面太多的话会造成webpack热更新太慢，所以开发环境不使用懒加载，只有生产环境使用懒加载
const _import = require('@/libs/util.import.' + process.env.NODE_ENV)

// fix vue-router NavigationDuplicated
const VueRouterPush = VueRouter.prototype.push
VueRouter.prototype.push = function push (location) {
  return VueRouterPush.call(this, location).catch(err => err)
}
const VueRouterReplace = VueRouter.prototype.replace
VueRouter.prototype.replace = function replace (location) {
  return VueRouterReplace.call(this, location).catch(err => err)
}

Vue.use(VueRouter)

/**
 * @description 创建在 layout 中显示的路由设置
 * @param {Array} routes 动态路由设置
 */
export function createRoutesInLayout (routes = []) {
  return [...routes]
}

// 在 layout 之外显示的路由
export const routesOutLayout = [
  { path: '/refresh', name: 'refresh', component: _import('/sys/function/refresh'), hidden: true },
  { path: '/redirect/:route*', name: 'redirect', component: _import('/sys/function/redirect'), hidden: true },
  { path: '/login', name: 'login', component: _import('/sys/login'), hidden: true },
  { path: '/404', name: '404', component: _import('/sys/error/404'), hidden: true },
  { path: '*', redirect: '/404', hidden: true }
]

// 默认的路由
export const constantRoutes = createRoutesInLayout().concat(routesOutLayout)

/**
 * @description 创建路由
 * @param {Array} routes 路由设置
 */
export const createRouter = (routes = []) => new VueRouter({
  scrollBehavior: () => ({ y: 0 }),
  routes
})

// 导出路由 在 main.js 里使用
const router = createRouter(constantRoutes)

/**
 * @description 重新设置路由
 * @param {Array} routes 额外追加的路由
 */
export function resetRouter (routes = []) {
  router.matcher = createRouter(routes).matcher
}
/**
 * 路由拦截
 * 权限验证
 */
router.beforeEach(async (to, from, next) => {
  // 确认已经加载多标签页数据
  await store.dispatch('zerovue/page/isLoaded')
  // 确认已经加载组件尺寸设置
  await store.dispatch('zerovue/size/isLoaded')
  // 进度条
  NProgress.start()
  // 关闭搜索面板
  store.commit('zerovue/search/set', false)
  const token = util.storage.get('token')
  // 如果是登录或者401直接放行
  if (to.path === '/login') {
    if (token) {
      next(from.fullPath)
      NProgress.done()
    } else {
      next()
    }
  } else if (token) {
    next()
  } else {
    // 没有登录的时候跳转到登录界面
    // 携带上登陆成功之后需要跳转的页面完整路径
    next('login')
    NProgress.done()
  }
})

router.afterEach(to => {
  // 进度条
  NProgress.done()
  // 多页控制 打开新的页面
  store.dispatch('zerovue/page/open', to)
  // 更改标题
  util.title(to.meta.title)
})

export default router
